package lz;

public class LZList<E> {
    private LNode<E> head;
    private LNode<E> tail;

    private int size;

    public void addFirst(E value) {
        LNode<E> newNode = new LNode<E>(null,value, null);
        if (head == null) {
            head = tail = newNode;
        } else {
            head.pre = newNode;
            newNode.next = head;
            head = newNode;
        }
        size++;
    }

    public void add(E value, int index) {
        if (index == 0) {
            addFirst(value);
        } else if (index == size) {
            addLast(value);
        } else {

        }
    }

    public LNode<E> getIndex(int index) {
        if(index <= 0 || index >= size) {
            throw new IllegalArgumentException("");
        }

        int middle = size / 2;
        LNode<E> current;
        if (index < middle) {
            current = head;
            for(int i=0; i<index; i++) {
                current = current.next;
            }
            return current;
        } else {
            current = tail;
            for(int i=size-1; i>index; i--) {
                current = current.pre;
            }
            return current;
        }
    }

    public void addLast(E value) {
        LNode<E> newNode = new LNode<E>(null, value,null);
        if (tail == null) {
            head = tail = newNode;
        } else {
            tail.next = newNode;
            newNode.pre = tail;
            tail = newNode;
        }
        size++;
    }

    public int length() {
        return size;
    }


    public void list() {
        while (head != null) {
            System.out.println(head.data);
            head = head.next;
        }
    }

    private static class LNode<E>{
        private LNode<E> pre;
        private LNode<E> next;
        private E data;

        public LNode(LNode<E> pre, E data, LNode<E> next) {
            this.pre = pre;
            this.data = data;
            this.next = next;
        }
    }

    public static void main(String[] args) {
         LZList<Integer> lgen = new LZList<Integer>();
         lgen.addLast(1);
         lgen.addLast(2);
         lgen.addLast(3);
         lgen.addLast(4);
         lgen.addLast(5);
         lgen.addLast(6);
//         lgen.list();
        System.out.println(lgen.length());
        System.out.println(lgen.getIndex(4).data);
    }
}
